<template>
	<a-table
		:bordered="{ wrapper: false, headerCell: true, bodyCell: true }"
		@page-change="(data) => (page.pageNo = data)"
		@page-size-change="(data) => (page.pageSize = data)"
		:hoverable="false"
		class="com-table"
		ref="target"
		v-bind="$attrs"
	>
		<template #columns>
			<template v-for="(item, colIndex) in columns" :key="item">
				<slot name="custom" :item="item">
					<a-table-column v-bind="item" :title="item.title" :data-index="String(item.field)">
						<template #cell="{ record, column, rowIndex }">
							<div class="column-item" @click="handelClick(rowIndex, colIndex, item, record)">
								<!-- 详情视图 -->
								<slot :name="item.slotName" v-if="getEdit(rowIndex, colIndex)" :header="item" :record="record">
									<fieldView :record="record" :item="item"> </fieldView>
								</slot>
								<!-- 编辑视图 -->
								<slot v-else :name="item.slotName + 'Edit'" :header="item" :record="record" :setToggle="setToggle">
									<fieldEdit v-model:toggle="toggle" @click.stop :record="record" :item="item" @update="(data) => emit('update', data, item)"> </fieldEdit>
								</slot>
							</div>
						</template>
					</a-table-column>
				</slot>
			</template>
			<!-- 占位column，把剩下的位置占满 -->
			<a-table-column cell-class="custom-column" v-if="columns.length"></a-table-column>
		</template>
	</a-table>
</template>

<script setup lang="ts">
import fieldView from "./components/fieldView.vue";
import fieldEdit from "./components/fieldEdit.vue";
import { onClickOutside } from "@vueuse/core";

const toggle = ref(false);
const target = ref(null);
const activeField: any = ref([]);

const emit = defineEmits(["update", "update:pageForm", "page-change"]);
const setToggle = (data) => {
	toggle.value = data;
};

onClickOutside(target, (event) => {
	if (activeField.value.length && !toggle.value) {
		activeField.value = [];
	}
});
const props = defineProps({
	columns: {
		type: Array as any,
		default: () => []
	},
	editConfig: {
		type: Object,
		default: () => {}
	},
	pageForm: {
		type: Object
	}
});

const getDisabled = (item, row) => {
	const f1 = !item.edit;
	if (props.editConfig?.disabled) {
		// 禁用字段
		const { field, value } = props.editConfig?.disabled;
		const flag = row[field] === value;
		return flag || f1;
	}
	return f1;
};
const handelClick = (rowIndex, colIndex, item, row) => {
	if (getDisabled(item, row)) return (activeField.value = []);
	activeField.value = [`${rowIndex}-${colIndex}`];
};
const getEdit = (rowIndex, colIndex) => {
	return !activeField.value.includes(`${rowIndex}-${colIndex}`);
};

const page = ref({
	pageNo: 1,
	pageSize: 10
});

watch(
	() => page.value,
	(data) => {
		emit("update:pageForm", data);
		emit("page-change");
	},
	{ deep: true }
);
</script>

<style lang="scss"></style>
